<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Shopcar extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('form');
	}

	/**
	 * 我的购物车列表
	 */
	public function index()
	{
		$shopcar = $this->session->userdata('shopcar');
		$price = array();
		$amount = array();
		
		//当有物品存在时候
		if($shopcar)
		{
			foreach ($shopcar as $value)
			{
				$price[] = $value['price']*$value['amount'];
				$amount[] = $value['amount'];
			}
		}
		else
		{
			$price[]= 0;
			$amount[] = 0;
		}
		
		$this->load->model("m_books");

		$total_price = array_sum($price);
		$total_amount = array_sum($amount);

		$data = array('title'=>'我的购物车 - 作业本教材网','h_title'=>'我的购物车','style' =>array('shopcar/index','shopcar/common'),'shopcar'=>$shopcar,'total_price'=>$total_price,'total_amount'=>$total_amount);
		
		$this->load->view('header',$data);
		$this->load->view('shopcar/index');
		$this->load->view('footer/simplefooter');
	}
	
	/**
	 * 用户下单成功
	 */
	public function order()
	{
		$shopcar = $this->session->userdata('shopcar');
		
		//如果购物车为空,则跳转回购物车页面
		if($shopcar)
		{
			$data=array('shopcar'=>$shopcar);
		
			$amount = array();
			foreach ($shopcar as $value) 
			{
				$price[] = $value['price']*$value['amount'];
				$amount[] = $value['amount'];
			}
			
			$total_price = array_sum($price);
			$total_amount = array_sum($amount);
				
			if(!$total_amount)
			{
				$shopcarResult = array('status'=>10601); //购物车为空
			}
			else
			{
				$shopcarResult = array('status'=>10000);
			}
		
		}
		else
		{
			$shopcarResult = array('status'=>10601); //购物车为空
		}
		
		if($shopcarResult['status'] == 10601)
		{
			header('location:'.base_url().'shopcar');
			exit;
		}
	
		$data = array('title'=>'订单结算页 - 作业本教材网',
				'h_title'=>'确认订单信息',
				'style' => array('shopcar/order','shopcar/common'),
				'shopcar'=>$shopcar,
				'total_price'=>$total_price,
				'total_amount'=>$total_amount
		);
		
		$this->load->view('header',$data);
		$this->load->view('shopcar/order');
		$this->load->view('footer/simplefooter');
	}
	
	/**
	 * 下单成功页面
	 */
	public function success()
	{
		$shopcar = $this->session->userdata('shopcar');
		if(!$shopcar)
		{
			//当购物车为空时候跳转到购物车首页
			header('location:'.base_url());
			exit;
		}
		$dist = $this->input->post();
		
		if(!$dist['user_name'])
		{
			exit('姓名不能为空');
		}
		
		if(strlen($dist['user_name']) > 150)
		{
			exit('姓名不能大于50个字');
		}
		
		if(!$dist['phoneNumber'])
		{
			exit('联系方式不为空');
		}

		if(!preg_match("/^1[3|4|5|7|8][0-9]\d{8}$/",$dist['phoneNumber']))
		{
			exit('联系方式不正确');
		}
		
		if(!$dist['address'])
		{
			exit('收货地址不能为空');
		}
		
		if(strlen($dist['user_name']) > 300)
		{
			exit('姓名不能大于100个字');
		}
		
		$order_session_user = array(
                   'order_username'  => $dist['user_name'],
                   'order_phoneNumber'     => $dist['phoneNumber'],
                   'order_address' => $dist['address']
               );

		$this->session->set_userdata($order_session_user);
				
		$price = array();
		
		//当有物品存在时候

		foreach ($shopcar as $value)
		{
			$price[] = $value['price']*$value['amount'];
		}
		
		$total_price = array_sum($price);

		$this->load->model('m_books');
		$this->load->model('m_order');
		
		$order_number = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
		
		//将用户订单插入数据库,插入zy_order表
		$order_info = array(
				'user_name'=>$dist['user_name'],//用户姓名
    			'phoneNumber'=>$dist['phoneNumber'],//手机号码
    			'address'=>$dist['address'],//用户详细地址
				'order_number'=>$order_number,//订单号
    			'user_remark'=>$dist['remark'],//用户备注
    		);
		$order_id = $this->m_order->insertOrder($order_info);
		
		$order_total_price = 0;
		//将用户订单详情加入数据库,插入zy_order_details表
		foreach ($shopcar as $value)
		{
			$book_info = $this->m_books->selectBookAmountById(substr($value['id'], 4));
			
			$order_info = array(
				'order_id'=>$order_id,
    			'price'=>$book_info['0']->book_price,//作业本价,需要直接从数据库读取，防止篡改
    			'book_quantity'=>$value['amount'],//发货日期
    			'book_id'=>substr($value['id'], 4)
    		);
    		
    		$order_total_price += ($book_info['0']->book_price * $value['amount']);
    		
			if($this->m_order->insertOrderDetail($order_info))
			{
				$this->m_order->updateOrderTotalPrice($order_id , $order_total_price);
				$this->m_books->reduceStoreAmount($value['amount'] , substr($value['id'], 4) );
			}
		}
		
		//送达日期
		
		$array_time = date("Y-m-d",strtotime("+1 days")).'（明天）';
		
		$data = array('title'=>'下单成功 - 作业本教材网',
				'h_title'=>'下单成功',
				'style' => array('shopcar/success','shopcar/common'),
				'total_price'=>$total_price?$total_price:'0',
				'arrive_date'=>$array_time,
				'order_id'=>$order_number
		);
		
		$this->clearShopCar();

		$this->load->view('header',$data);
		$this->load->view('shopcar/success');
		$this->load->view('footer/simplefooter');
	}
	
	/**
	 * 添加商品到购物车
	 * 主要提供给前台Ajax使用
	 * 
	 */
	public function addShopCarAjax()
	{
		$car = $this->input->post();
		$session_car = $this->session->userdata('shopcar');
		
		//把之前的商品拼在现在商品之前，一起加入session
		if($session_car)
		{
			foreach ($session_car as $key => $value) 
			{
				$data['shopcar'][$key] = $value;
			}
		}
		
		//计算现在购物车中有多少物品
		if(isset($session_car['suk_'.$car['id']]))
		{
			//当这件商品已经存在于购物车之中时候
			$book_qty = $session_car['suk_'.$car['id']]['amount'] + $car['qty'];
		}
		else
		{
			//当这件商品不在购物车
			$book_qty = (int)$car['qty'];
		}


		$this->load->model('m_books');
		$book_info = $this->m_books->selectBookById($car['id']);
		
		//当库存充足的时候
		if($book_qty <= $book_info['0']->book_store)
		{
			$data['shopcar']['suk_'.$car['id']] =array('id'=>'suk_'.$car['id'],'amount'=>$book_qty,'price'=>$book_info['0']->book_price);
			$this->session->set_userdata($data);

			$shopcar = $this->session->userdata('shopcar');

			$price = array();
			$amount = array();
			foreach ($shopcar as $value) 
			{
				$price[] = $value['price']*$value['amount'];
				$amount[] = $value['amount'];
			}

			$total_price = array_sum($price);
			$amount = array_sum($amount);
			$shopcarJson = array('amount'=>$amount,'price'=>$total_price); //现在购物车的数量以及价格
		}
		else
		{
			$shopcarJson = array('store_warn'=>'1'); //库存不足
		}
		
		echo json_encode($shopcarJson);
	}
	
	/**
	 * 更新购物车
	 * 一般用于我的购物车列表直接增加物品所用
	 */
	public function updateShopCar()
	{
		$car = $this->input->post();
		$session_car = $this->session->userdata('shopcar');

		if($car['type']=='increase')
		{
			$book_qty = $session_car['suk_'.$car['id']]['amount'] + 1;
		}
		elseif($car['type']=='decrease')
		{
			$book_qty = $session_car['suk_'.$car['id']]['amount'] - 1;
		}
		elseif($car['type']=='userinput')
		{
			$book_qty = $car['amount'];
		}
		
		//如果物品数量小于1，则提示本商品一件起卖
		if($book_qty == 0)
		{
			$shopcarJson = array('status'=>10603);
			echo json_encode($shopcarJson);
			exit;
		}
		
		$this->load->model('m_books');
		$books = $this->m_books->selectBookAmountById($car['id']);

		if($book_qty <= $books['0']->book_store)
		{
			$session_car['suk_'.$car['id']] =array('id'=>'suk_'.$car['id'],'amount'=>$book_qty,'price'=>$books['0']->book_price);
			$data = array('shopcar'=>$session_car);
			$this->session->set_userdata($data);

			$shopcar = $this->session->userdata('shopcar');
			$price = array();
			$amount = array();
			foreach ($shopcar as $value) {
				$price[] = $value['price']*$value['amount'];
				$amount[] = $value['amount'];
			}
			$total_price = array_sum($price);
			$amount = array_sum($amount);
			$shopcarJson = array('status'=>10000,'amount'=>$amount,'price'=>$total_price); //success
		}
		else
		{
			$shopcarJson = array('status'=>10602); //库存不足
		}

		echo json_encode($shopcarJson);
	}
	
	/**
	 * 删除购物车中物品
	 * 给前台Ajax使用
	 * 
	 * @param int $suk_id 待从购车中删除的物品的ID号
	 * 
	 * @return Json 删除后商品的列表,用于展示
	 */
	public function deleteShopcar($suk_id)
	{
		$shopcar = $this->session->userdata('shopcar');
		
		//先清除掉购物车内所有物品
		$this->session->unset_userdata('shopcar');

		unset($shopcar[$suk_id]);

		if($shopcar)
		{
			$data=array('shopcar'=>$shopcar);
			
			//再将剩余的物品加入到购物车里面
			$this->session->set_userdata($data);
			$shopcar = $this->session->userdata('shopcar');

			$price = array();
			$amount = array();
			foreach ($shopcar as $value) {
				$price[] = $value['price']*$value['amount'];
				$amount[] = $value['amount'];
			}

			$total_price = array_sum($price);
			$amount = array_sum($amount);

			$shopcarJson = array('amount'=>$amount,'price'=>$total_price,'success'=>'1');
		}
		else
		{
			$shopcarJson = array('amount'=>0,'price'=>0,'success'=>'2');
		}

		
		echo json_encode($shopcarJson);
		
	}

	public function clearShopCar()
	{
		$this->session->unset_userdata('shopcar');
	}
	
	public function showsession()
	{
		$shopcar = $this->session->userdata('shopcar');
		var_dump($shopcar);
	}
	
	/**
	 * 检测购物车是否为空
	 */
	public function checkShopCar()
	{
		$shopcar = $this->session->userdata('shopcar');

		$this->load->model("m_books");
		
		if($shopcar)
		{
			$data=array('shopcar'=>$shopcar);

			$amount = array();
			foreach ($shopcar as $value) {
				$store_num = $this->m_books->selectBookAmountById(substr($value['id'],4));
				
				if($store_num['0']->book_store < $value['amount'])
				{
					echo '{"status":"10602","name":"'.$store_num['0']->book_name.'"}';
					exit;
				}
				$amount[] = $value['amount'];
			}

			$amount = array_sum($amount);
			
			if(!$amount)
			{
				$shopcarResult = array('status'=>10601); //购物车为空
			}
			else 
			{
				$shopcarResult = array('status'=>10000);
			}

		}
		else
		{
			$shopcarResult = array('status'=>10601); //购物车为空
		}
		
		echo json_encode($shopcarResult);
	}
}

/* End of file fenzhong.php */
/* Location: ./application/controllers/fenzhong.php */